from django.db import models

# get_facebook_client lets us get the current Facebook object
# from outside of a view, which lets us have cleaner code
from facebook.djangofb import get_facebook_client

from cv.models import LearnerInformation, Education, WorkExperience, Language

from django.utils.translation import ugettext as _ #For internationalization

class UserManager(models.Manager):
    """Custom manager for a Facebook User."""
    
    def get_current(self):#, my_request=None):
        """Gets a User object for the logged-in Facebook user."""
        facebook = get_facebook_client()
        user, created = self.get_or_create(id=int(facebook.uid))
        if created:
            #request = my_request
            # we could do some custom actions for new users here...
            # damn skippy -ADV
            l = LearnerInformation()
            
            # Populate the new LearnerInformation object with basic info.
            try:
                queryList = ['first_name', 'last_name']
                resultDict = facebook.users.getInfo([facebook.uid], queryList)[0]
                l.firstname = resultDict['first_name']
                l.lastname = resultDict['last_name']
            except:
                # If any of the above fails, populate the object with known safe values before saving.
                l.firstname = _("Firstname")
                l.lastname = _("Lastname")
                l.save()
            else: # the finally: keyword doesn't work until Python 2.5 gah!
                l.save()
            user.learner_information = l
            user.save()
            
            # Populate with current_location info.
            try:
                queryList = ['current_location']
                resultDict = facebook.users.getInfo([facebook.uid], queryList)[0]
                l.municipality = "%s, %s" % (resultDict['current_location']['city'], resultDict['current_location']['state'])
                l.postalCode = resultDict['current_location']['zip']
                # TODO# l.country = resultDict['current_location']['country']
            except:
                # If we fail to get current_location information, don't worry about it.
                pass
            else:
                l.save()

            # Populate with Education history info
            try:
                queryList = ['education_history']
                resultDict = facebook.users.getInfo([facebook.uid], queryList)[0]
                #debug# l.annexes = str(resultDict)
                #debug# l.save()
                for education_info in resultDict['education_history']:
                    e = Education()
                    e.learner_information = l
                    e.title = education_info['degree']
                    e.organization = education_info['name']
                    e.skills = ', '.join(education_info['concentrations'])
                    e.save()
            except:
                #If we didn't get education_info, don't worry about it.
                pass
                
            # Populate with work history info
            try:
                queryList = ['work_history']
                resultDict = facebook.users.getInfo([facebook.uid], queryList)[0]
                #debug# l.additional = str(resultDict)
                #debug# l.save()
                for work_information in resultDict['work_history']:
                    w = WorkExperience()
                    w.learner_information = l
                    w.title = work_information['position']
                    w.employer = '\n'.join([
                        work_information['company_name'],
                        ', '.join([
                            work_information['location']['city'],
                            work_information['location']['state'],
                            work_information['location']['country'],
                        ])
                    ])# whew                        
                    w.activities = work_information['description']
                    w.save()
            except:
                #If we didn't get work_history, don't worry about it.
                pass
                
        return user

class User(models.Model):
    """A simple User model for Facebook users."""

    # We use the user's UID as the primary key in our database.
    id = models.IntegerField(primary_key=True)

    # TODO: The data that you want to store for each user would go here.
    # For this sample, we let users let people know their favorite progamming
    # language, in the spirit of Extended Info.
    learner_information = models.OneToOneField(LearnerInformation, null=True) #Allow null so they can save initially.

    # Add the custom manager
    objects = UserManager()

    def __unicode__(self):
        return u'%s' % self.id

    class Admin:
        pass
